/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.log4j.Priority;
import org.apache.log4j.Logger;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;

/**
 *
 * @author freixo
 */
public class PDFUtils {

    public static String pdftoText(String fileName) {

        File f = new File(fileName);
        return pdftoText(f);

    }

    public static String pdftoText(File file) {
        PDFParser parser;
        String parsedText;
        PDFTextStripper pdfStripper;
        PDDocument pdDoc = null;
        COSDocument cosDoc = null;


//        System.out.println("Parsing text from PDF file " + file.getName() + "....");
        File f = file;

        if (!f.isFile()) {
//            System.out.println("File " + file.getName() + " does not exist.");
            //@todo lanzar excepcion
            return null;
        }

        try {
            parser = new PDFParser(new FileInputStream(f));
        } catch (Exception e) {
//            System.out.println("Unable to open PDF Parser.");
            //@todo lanzar excepcion            
            return null;
        }

        try {
            parser.parse();
            cosDoc = parser.getDocument();
            pdfStripper = new PDFTextStripper();
            pdDoc = new PDDocument(cosDoc);
            parsedText = pdfStripper.getText(pdDoc);
        } catch (Exception e) {
            System.out.println("An exception occured in parsing the PDF Document.");
            e.printStackTrace();
            //@todo lanzar excepcion            
            return null;
        } finally {
            if (cosDoc != null) {
                try {
                    cosDoc.close();
                } catch (IOException ex) {
                    Logger.getLogger(PDFUtils.class.getName()).log(Priority.FATAL, null, ex);
                }
            }

            if (pdDoc != null) {
                try {
                    pdDoc.close();
                } catch (IOException ex) {
                    Logger.getLogger(PDFUtils.class.getName()).log(Priority.FATAL, null, ex);
                }
            }

        }
//        System.out.println("Done.");
        return parsedText;
    }
}
